<?php
/**
 * PTemplate class
 * Template system for Pholow.
 *
 * @author Patrice Ferlet <metal3d@copix.org> 
 * @package core
 * @license http://opensource.org/licenses/lgpl-3.0.html GNU Lesser General Public License Version 3.0 (LGPLv3)
*/
class PTemplate extends PStandardObject{

    public function __construct(){

    }

    public function fetch($templatename,$fromModule=TRUE){

        if(!$fromModule) {
            //we will fetch theme template
            $content = file_get_contents($templatename);
        }
        else{
            //from module actions we will fetch template inside module.
            //TODO: manage fetching themed templates
            $path = _kernel()->getConfiguration()->get('root/paths')->name('modules@path').'/'._kernel()->getParam('module').'/templates';
        }
        
        if(strtolower(substr($templatename,-3))=="php"){
            //template is .php file
            $tpl = _obj();
            foreach($this->vars as $key=>$var)
                $tpl->$key = $var;
            ob_start();
            include $path.'/'.$templatename;
            return ob_get_clean();
        }

        //else
        if(isset($path)) 
            $content = file_get_contents($path.'/'.$templatename);
        //assign variables
        foreach ($this->vars as $key=>$var){
            $content = preg_replace('/<'.$key.'s*\/>/',$var,$content);
        }
        $content = preg_replace_callback('/<RESOURCE (.*?)\/>/',create_function ('$matches','return _resource($matches[1]);'),$content);
        return $content;
    }

    public function assignXMLStruct(PXMLElement $struct, $datas){
        foreach ($struct->struct as $var){
            if($var['name']==="var"){
                $key =$var['attributes']['value'];
                $this->vars[$key] = $datas->$key;
            }
        }

    }
}
